package business;
import java.io.Serializable;
import java.util.List;

import model.Atua;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.exception.ConstraintViolationException;

import util.HibernateUtil;

public class AtuaDAO implements Serializable {
	private static final long serialVersionUID = 3698257501498506444L;
	static AtuaDAO instance;
	
	public static AtuaDAO getInstance()
	{
		if(instance == null)
			instance = new AtuaDAO();
		return instance;
	}
	public AtuaDAO()
	{
	}
	public Atua get(int id) 
	{		
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		Atua item = (Atua)session.get(Atua.class,id);		
		tr.commit();
		return item;
	}
	
	public void salvar(Atua atua) {
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		try {
			session.saveOrUpdate(atua);
			tr.commit();
		} catch (ConstraintViolationException e) {
			tr.rollback();
			throw e;
		}
		return;
	}
	
	public  void remover(int id) {
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		session.delete(session.get(Atua.class, id));
		tr.commit();
		return ;
	}
	@SuppressWarnings("unchecked")
	public List<Atua> listar() {
		List<Atua> lista;
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		Criteria cr = session.createCriteria(Atua.class);
		cr.addOrder(Order.asc("associadoId"));
		cr.addOrder(Order.asc("ordemPreferencia"));
		lista = cr.list();
		tr.commit();
		return lista;
	}
	@SuppressWarnings({ "unchecked" })
	public List<Atua> listar(int associadoId) {
		List<Atua> lista;
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		Criteria cr = session.createCriteria(Atua.class);
		cr.add(Restrictions.eq("associadoId", associadoId));
		cr.addOrder(Order.asc("ordemPreferencia"));
		lista = cr.list();
		tr.commit();
		return lista;
	}
}